package com.top75;

import com.bean.TreeNode;

/**
 * @Author: huangzhigao
 * @Date: 2023/5/23 20:39
 */
public class Code236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (p == null || q == null) {
            return root;
        }

        TreeNode leftParent = lowestCommonAncestor(root.left, p, q);
        TreeNode rightParent = lowestCommonAncestor(root.right, p, q);
        if (leftParent != null && rightParent != null) {
            return root;
        }
        if (leftParent == null && rightParent == null) {
            return null;
        }
        return leftParent != null ? leftParent : rightParent;

    }
}
